import './styles.css';
import React, { useState } from 'react';
import CartItem from './components/CartItem';

interface Product {
  id: number;
  name: string;
  price: number;
  quantity: number;
  image: string;
  origin: string;
  specifications: string;
}

const Cart: React.FC = () => {
  const [items, setItems] = useState<Product[]>([
    { id: 1, name: 'Gold Necklace', price: 500, quantity: 1, image: 'https://img.zcool.cn/community/0165b158fa21f0a8012160f7c5663f.jpg@1280w_1l_2o_100sh.jpg', origin: 'Italy', specifications: '18K Gold' },
    { id: 2, name: 'Silver Ring', price: 200, quantity: 2, image: 'https://th.bing.com/th/id/R.18bd718947a6e5a1f4bde3a6e547f2f7?rik=rSzqvViEPM0OPA&riu=http%3a%2f%2fwww.timenetwork.com.cn%2fuploadfile%2f2023%2f0219%2f20230219110513744.jpg&ehk=NnjvHxAf%2bLiRQ4lLnS4afkjKsKqJODnjQOQ2mYe%2bKt8%3d&risl=&pid=ImgRaw&r=0', origin: 'USA', specifications: 'Sterling Silver' },
    { id: 3, name: 'Diamond Earrings', price: 1200, quantity: 1, image: 'https://th.bing.com/th/id/R.5272d960ceb451752cd82abfc0efcd9c?rik=IWwunszrdOSJ4A&riu=http%3a%2f%2fwww.myunmei.com%2fupload%2fueditor%2fimage%2f20230525%2f1685023969405025730.jpg&ehk=mgyxtdQfz1LhzxnwmN75BsVzNuuuqR%2baEc0R62BPca8%3d&risl=&pid=ImgRaw&r=0', origin: 'South Africa', specifications: 'Certified Diamond' },
  ]);

  const [selectedItems, setSelectedItems] = useState<number[]>([]);
  const [selectAll, setSelectAll] = useState(false);

  const handleSelectAll = () => {
    if (selectAll) {
      setSelectedItems([]);
    } else {
      setSelectedItems(items.map(item => item.id));
    }
    setSelectAll(!selectAll);
  };

  const handleSelect = (id: number) => {
    setSelectedItems(prev => [...prev, id]);
  };

  const handleDeselect = (id: number) => {
    setSelectedItems(prev => prev.filter(itemId => itemId !== id));
  };

  const handlePriceChange = (id: number, newPrice: number) => {
    setItems(prevItems =>
      prevItems.map(item =>
        item.id === id ? { ...item, price: newPrice } : item
      )
    );
  };

  const handleQuantityChange = (id: number, newQuantity: number) => {
    setItems(prevItems =>
      prevItems.map(item =>
        item.id === id ? { ...item, quantity: newQuantity } : item
      )
    );
  };

  return (
    <div className="cart">
      <button onClick={handleSelectAll}>
        {selectAll ? 'Deselect All' : 'Select All'}
      </button>
      {items.map(item => (
        <CartItem
          key={item.id}
          id={item.id}
          name={item.name}
          price={item.price}
          quantity={item.quantity}
          image={item.image}
          origin={item.origin}
          specifications={item.specifications}
          onSelect={handleSelect}
          onDeselect={handleDeselect}
          onPriceChange={handlePriceChange}
          onQuantityChange={handleQuantityChange}
          selected={selectedItems.includes(item.id)}
        />
      ))}
    </div>
  );
};

export default Cart;
